package cn.eud.hunau.controller;

import cn.eud.hunau.common.BindingResultParseMessage;
import cn.eud.hunau.common.R;
import cn.eud.hunau.common.JwtUtil;
import cn.eud.hunau.common.Result;
import cn.eud.hunau.mapper.MovieMapper;
import cn.eud.hunau.pojo.Movie;
import cn.eud.hunau.pojo.RecommendRequest;
import cn.eud.hunau.pojo.User;
import cn.eud.hunau.request.UserReq;
import cn.eud.hunau.service.RatingService;
import cn.eud.hunau.service.UserService;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RequestMapping("/user")
@RestController
public class UserController {

    @Resource//JDK (JSR-250)，默认按名称，找不到才按类型
    private UserService userService;
    @Autowired
    private RatingService ratingService;
    @Autowired
    private MovieMapper movieMapper;

    @PostMapping("/login")
    public R login(@RequestBody   @Valid UserReq user, BindingResult bindResult){// 紧跟在被校验参数的后面声明

        if(bindResult.hasErrors()){
            // 链式调用，从左到右调用，从右到左返回
            return R.error().message(BindingResultParseMessage.parseDefaultMessage(bindResult));
        }

       User u= userService.login(user);

       // 获取 JWT 令牌
       String token = JwtUtil.generateToken(u.getId());

       // 成功返回
       return R.ok().data("token", token);
    }

    @PostMapping("/register")
    public R register(@RequestBody @Valid UserReq user, BindingResult bindResult) {

        // 返回错误信息
        if (bindResult.hasErrors()) {
            return R.error().message(BindingResultParseMessage.parseDefaultMessage(bindResult));
        }

        boolean success = userService.register(user);
        return success ? R.ok().message("注册成功") : R.error().message("注册失败");
    }



    @PostMapping("/svd")
    public Result<List<Movie>> recommend(@RequestBody RecommendRequest request) {
        Long userId = request.getUserId();
        int topN = request.getTopN() != null ? request.getTopN() : 5;
        List<Long> recMovieIds = ratingService.recommend(userId, topN);

        List<Movie> movies = recMovieIds.isEmpty() ? List.of() : movieMapper.selectInIds(recMovieIds);
        System.out.println("userId = " + userId + ", recMovieIds = " + recMovieIds);
        return new Result<>(0, "success", movies);
    }
}
